package com.sky.service.impl;


import com.sky.dto.GoodsSalesDTO;

import com.sky.entity.Orders;

import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkSpaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.jdbc.SQL;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private WorkSpaceService workSpaceService;
    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        //统计指定时间期间的营业额数据，就是订单状态已完成的订单的总金额
        //第一步：先计算出日期，当前集合用于存放从begin到end范围内的每天的日期
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while(!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        dateList.add(end);
        //使用StringUtils.join方法，将dateList集合中的元素用逗号拼接起来,变成字符串的形式
        TurnoverReportVO turnoverReportVO = TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .build();
        //第二步：根据指定的日期计算营业额的金额
        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date:dateList){
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap();
            map.put("begin",beginTime);
            map.put("end",endTime);
            map.put("status",Orders.COMPLETED);
            Double turnover= orderMapper.sumByMap(map);
            turnoverList.add(turnover == null ? 0.0 : turnover);
        }
        turnoverReportVO.setTurnoverList(StringUtils.join(turnoverList,","));
        return turnoverReportVO;
    }

    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        //根据前端发送的起始时间和中止时间进行计算日期，并封装成集合
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals( end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        dateList.add(end);
        //创建用户总数的集合
        List< Integer> totalUserList = new ArrayList<>();
        //创建新增用户的集合
        List< Integer> newUserList = new ArrayList<>();
        //遍历日期的集合，动态创建传递的参数
        for (LocalDate date:dateList){
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //一开始先使用map集合创建一个end的参数，然后获取指定日期之前的所有的用户总数
            Map map = new HashMap();
            map.put("end",endTime);
            //根据这个参数查询用户总数
            Integer totalUser = userMapper.getUserCount(map);
            totalUserList.add(totalUser);
            //在map集合中增加begin参数，然后获取指定日期之后的用户总数
            map.put("begin",beginTime);
            Integer newUser = userMapper.getUserCount(map);
            newUserList.add(newUser);
        }
        //创建UserReportVO对象，并返回
        UserReportVO userReportVO =UserReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .totalUserList(StringUtils.join(totalUserList,","))
                .newUserList(StringUtils.join(newUserList,","))
                .build();
        return userReportVO;
    }

    @Override
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {
        //根据发送日期的起始时间和中止时间进行计算日期，并封装成集合,
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while(!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        dateList.add(end);
        //创建每日订单数的集合
        List<Integer> orderCountList = new ArrayList<>();
        //创建每日有效订单数的集合
        List<Integer> validOrderCountList = new ArrayList<>();
        //遍历日期的集合，创建动态的参数，并查询数据库,每日订单数是下订单的个数，有效订单数是每天已完成的订单数
        for (LocalDate date:dateList){
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap();
            map.put("begin",beginTime);
            map.put("end",endTime);
            Integer orderCount = orderMapper.getOrderCount(map);
            orderCountList.add(orderCount);
            map.put("status",Orders.COMPLETED);
            Integer validOrderCount = orderMapper.getOrderCount(map);
            validOrderCountList.add(validOrderCount);
        }
        //计算订单总数，有效订单数，订单完成率
        //使用流的形式，将集合中的元素转换成int类型，并求和
        Integer totalOrderCount = orderCountList.stream().mapToInt(Integer::intValue).sum();
        Integer validOrderCount = validOrderCountList.stream().mapToInt(Integer::intValue).sum();
        Double orderCompletionRate = 0.0;
        if(totalOrderCount != 0){
            orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;
        }
        //创建OrderReportVO对象，并返回
        OrderReportVO orderReportVO = OrderReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .validOrderCountList(StringUtils.join(validOrderCountList,","))
                .orderCountList(StringUtils.join(orderCountList,","))
                .validOrderCount(validOrderCount)
                .totalOrderCount(totalOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
        return orderReportVO;
    }

    @Override
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        //根据日期的起始时间和中止时间获取这段时间内的前10条的商品名称和销量数据，这个订单的状态应该是已完成的，不考虑其他状态的订单的数据
        //1、先将LocalDate的时间转为LocalDateTime的时间的格式
        LocalDateTime beginTime = LocalDateTime.of(begin,LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end,LocalTime.MAX);
        //2、通过调用mapper中的方法来获取名字和销量对象的集合
        List<GoodsSalesDTO> goodsSalesDTOList = orderDetailMapper.getSalesTop10(beginTime,endTime);
        //3、获取集合中的名字然后将其转为集合的形式
        List<String> goodsNameList = goodsSalesDTOList.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        //4、获取集合中的销量然后将其转为集合的形式
        List<Integer> goodsSalesList = goodsSalesDTOList.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        //5、封装SalesTop10ReportVO进行封装
        SalesTop10ReportVO salesTop10ReportVO = SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(goodsNameList,","))
                .numberList(StringUtils.join(goodsSalesList,","))
                .build();
        return salesTop10ReportVO;
    }

    @Override
    public void exportBusinessData(HttpServletResponse response) {
        //1、查询数据库，获取数据,指定时间期间，查询30天的日期
        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);
        LocalDateTime beginTime = LocalDateTime.of(dateBegin,LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(dateEnd,LocalTime.MAX);
        //获取概览数据，
        BusinessDataVO businessDataVO = workSpaceService.getBusinessData(beginTime,endTime);
        //2、获取输入流的文件
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/reportStatistics.xlsx");
        if (in == null) {
            throw new RuntimeException("模板文件未找到！请检查路径: template/reportStatistics.xlsx");
        }
        try {
            //基于模版文件创建一个excel文件
            XSSFWorkbook excel = new XSSFWorkbook(in);
            //获取标签页
            XSSFSheet sheet = excel.getSheet("Sheet1");
            //填充第二行的数据
            sheet.getRow(1).getCell(1).setCellValue("时间："+dateBegin+"至"+dateEnd);
            //填充第四行的数据，营业额，订单完成率，新用户数
            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());
            //填充第5行的数据,有效订单数，平均客单价
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            row.getCell(4).setCellValue(businessDataVO.getUnitPrice());
            //填充详细的数据
            for (int i = 0; i < 30; i++) {
                LocalDate date = dateBegin.plusDays(i);
                //获取当前天的数据
                BusinessDataVO businessData =workSpaceService.getBusinessData(LocalDateTime.of(date,LocalTime.MIN),LocalDateTime.of(date,LocalTime.MAX));
                XSSFRow row1 = sheet.getRow(7+i);
                row1.getCell(1).setCellValue(date.toString());
                row1.getCell(2).setCellValue(businessData.getTurnover());
                row1.getCell(3).setCellValue(businessData.getValidOrderCount());
                row1.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row1.getCell(5).setCellValue(businessData.getUnitPrice());
                row1.getCell(6).setCellValue(businessData.getNewUsers());
            }
            //3、将excel文件写入到输出流中，并设置文件名
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

            //关闭资源
            out.close();
            excel.close();
            in.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}
